import datetime
import hashlib
from functools import wraps

import jwt
from flask import request, jsonify

from utils.tools import json_response
from utils.work_log import get_logger

JWT_SECRET_KEY = 'mi_gong@!#@#123i1you2'
log = get_logger(__name__)


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        token = request.headers.get("mi_token") or request.cookies.get('mi_token')
        log.info("login_required token:" + str(token))
        try:
            if token:
                # todo 检验签名是否过期，密码正确etc
                obj = encode_jwt(token)
                if not obj:
                    return json_response('', msg='Token缺失!', code=-99)
                kwargs.update(obj.get('data'))
                return func(*args, **kwargs)
            else:
                return jsonify({'data': '', 'msg': 'Token为空!', 'code': -99})
        except Exception as ex:
            log.error(ex)
            log.error("login_required token error")
            return jsonify({'data': '', 'msg': 'Token错误!', 'code': -99})

    return wrapper


def gene_auth_code(user_info):
    """
    生成授权码
    :param user_info:
    :return:
    """
    m = hashlib.md5()
    raw_str = "%s-%s-%s-%s" % (user_info.uid,
                               user_info.login_name,
                               user_info.login_pwd,
                               user_info.salt)
    m.update(raw_str.encode("utf-8"))
    return m.hexdigest()


def hash_password(password, salt):
    """
    hash密码
    :param password:
    :param salt:
    :return:
    """
    m = hashlib.md5()
    raw_str = password + salt
    m.update(raw_str.encode("ascii"))
    return m.hexdigest()


def create_jwt(some, aud='migong'):
    """
    生成jwt
    :param some:
    :param aud:
    :return:
    """
    date_time_int = datetime.datetime.now() + datetime.timedelta(days=7)
    option = {
        'exp': date_time_int,
        'aud': aud,
        'data': some
    }
    encoded2 = jwt.encode(option, JWT_SECRET_KEY, algorithm='HS256')
    return encoded2.decode('utf-8')


def encode_jwt(token, aud='migong'):
    """
    解析jwttoken
    :param token:
    :param aud:
    :return:
    """
    decoded = jwt.decode(token, JWT_SECRET_KEY, audience=aud, algorithms=['HS256'])
    return decoded


def get_user():
    req_token = request.headers.get("mi_token") or request.cookies.get('mi_token')
    if not req_token:
        log.info("mi token is null")
        return None
    data = encode_jwt(req_token)
    if data and data.get('data'):
        content_data = data.get("data")
        log.info("content_data===:" + str(content_data))
        return {'user_id': content_data.get("user_id"),
                'tel': content_data.get("tel"),
                'wx_openid': content_data.get("wx_openid")}


def get_user_id():
    e_user = get_user()
    if e_user:
        return e_user.get("user_id")


#
if __name__ == '__main__':
    t_user = {"user_id": 21,
              "tel": '',
              "wx_openid": 'olv5c5UuwH9zEBXTScgF9TNPQTp8'}
    token = create_jwt(t_user)
    print(token)
    result = encode_jwt(token)
    print(result)
    pass
